package ca.cbc.msb.mq;

import javax.jms.JMSException;
import javax.naming.NamingException;

import ca.cbc.msb.util.ProgressReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.cbc.medialib.entity.Media;
import ca.cbc.medialib.exception.ThePlatformObjectNotFoundException;
import ca.cbc.medialib.service.MediaService;
import ca.cbc.medialib.util.ApplicationContextUtil;
import ca.cbc.msb.entity.MSBMessage;
import ca.cbc.msb.mobilemedia.MobileMediaService;
import ca.cbc.msb.mobilemedia.YospaceServiceImpl;
import ca.cbc.msb.mobilemedia.YospaceStatus;
import ca.cbc.msb.persistence.FailedMediaPersistence;
import ca.cbc.msb.persistence.MediaPersistence;
import ca.cbc.msb.persistence.ProcessingStatusPersistence;
import ca.cbc.msb.util.AppConfig;
import ca.cbc.msb.util.FTPUtil;

/**
 * JMS implementation of MessageHandler for verifivation media status after submitted to yoSpace.
 *
 * @author usr
 */
public class VideoVerificationMessageHandler implements MessageHandler {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    private static boolean IS_DELETE_AFTER_UPLOAD;
    private MediaService mediaService;
    private MobileMediaService mobileMediaService;
    private MediaPersistence mediaPersistence;
    private FailedMediaPersistence failedMediaPersistence;
    private ProcessingStatusPersistence processingStatusPersistence;

    public VideoVerificationMessageHandler() {
        IS_DELETE_AFTER_UPLOAD = AppConfig.getProperty("delete.after.upload").equalsIgnoreCase("true") ? true : false;
        mediaService = new MediaService();
        mobileMediaService = new YospaceServiceImpl();
       	mediaPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(MediaPersistence.class);
    	failedMediaPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(FailedMediaPersistence.class);
    	processingStatusPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(ProcessingStatusPersistence.class);  	
    }

    @Override
    public void handle(MSBMessage message, MessageUtil messageUtil) throws NamingException,
            JMSException {
    	log.debug(">>>VideoVerificationMessage Received ({})", message);
        Media media = message.getMedia();
        long releaseId = media.getReleaseId();
        long yospaceId = media.getMobileId();
        boolean isSumbitToYospace = false;
        
        try{
	        YospaceStatus status = mobileMediaService.getStatus(yospaceId);
	        log.info("Media submitted to Yospace ({}), waiting for verification...", yospaceId);
	        
	        if (status == YospaceStatus.PROCESSING_IN_PROGRESS) {
	            messageUtil.rollback();
	            log.info("{} In Progress, session rolled back", media.toString());
	            isSumbitToYospace = true;
	        } else { //process finished       
		        messageUtil.commit(); //commit receive notification message
		        
		        if (status == YospaceStatus.READY_FOR_USE) {
		            //delete from ftp
		            if (IS_DELETE_AFTER_UPLOAD) {
		                FTPUtil.deleteFile(media.getOriginalFileName());
		            }
		            log.info("Yospace verification done for {}, submitting yospaceID to thePlatform", media.toString());
		            try {
		                //update theP with yospaceId
		                mediaService.saveYospaceId(releaseId, yospaceId);
		                log.info("Add yospaceId ({}) to thePlatform with message ({}) successfully ", yospaceId, message);
		                
		                //save to db
		                mediaPersistence.saveOrMerge(media);
		                
		                log.info("Processing finished successfully for {}", media.toString());
		                ProgressReport.instance.statusReport(message, "Processing Successful. Process Finished/" );
		            } catch (ThePlatformObjectNotFoundException e) {
		                log.error("!!!Error in submission yospace, clip deleted fro theP..." + media.toString(), e);
		                ProgressReport.instance.report("Could not add yospace id to theP for media {}", message);
		         
		                mobileMediaService.deleteMedia(yospaceId);
		                failedMediaPersistence.save(media);
		            }
		        } else {
		            //yospace submission failed, this clip is not gona available in mobile
		            log.error("!!!Error in submission to Yospace with return status {} and YospaceVerificationMessage ({})", status, message);
		            failedMediaPersistence.save(media);
		        }
	        }
        } catch (Exception e) {
        	failedMediaPersistence.save(media);
        	log.error("Unkonw error when processing changed media, abort further action.", e);
        } finally { //will remove processing flag
        	if(!isSumbitToYospace) {
        		processingStatusPersistence.removeProcessingFlag(message);
        	}
        }
    }
}
